package com.chinasolf.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinasoft.model.cmn.Dict;
import com.chinasoft.vo.cmn.DictEeVo;
import com.chinasolf.yygh.cmn.listener.DictListener;
import com.chinasolf.yygh.cmn.mapper.DictMapper;
import com.chinasolf.yygh.cmn.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-03-17
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictListener dictListener;

    @Cacheable(value = "dict", key = "'selectIndexList' + #id")
    @Override
    public List<Dict> getChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildData(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;

    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Dict> list = baseMapper.selectList(null);
            ArrayList<DictEeVo> listVo = new ArrayList<>();
            for (Dict dict : list) {
                DictEeVo dictEeVo = new DictEeVo();
//                dictEeVo.setId(dict.getId());
//                dictEeVo.setParentId(dict.getParentId());
                BeanUtils.copyProperties(dict, dictEeVo);
                listVo.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(listVo);
        } catch (Exception e) {

        }
    }

    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据编号获取对应名称
    //value就是编号
    //dictCode为了查询id不唯一的时候使用
    @Override
    public String getNameByCode(String value, String dictCode) {

        if (StringUtils.isEmpty(dictCode)) {
            //唯一
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (dict != null){
                return dict.getName();
            }
        } else {
            //不唯一
            Dict dictParent = this.getParentByDictCode(dictCode);
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id",dictParent.getId());
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (dict != null){
                return dict.getName();
            }
        }
        return null;
    }

    @Override
    public List<Dict> getByDictCode(String dictCode) {
        Dict dictParent = this.getParentByDictCode(dictCode);
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",dictParent.getId());
        List<Dict> list = baseMapper.selectList(wrapper);
        return list;
    }

    private Dict getParentByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }

    private boolean isChildData(Long dictId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", dictId);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }
}
